<?php

namespace app\index\service;

use app\common\job\TradeEnd;
use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\model\ConsultingQuestion;
use app\common\model\ConsultingServer;
use app\common\model\Member;
use app\common\model\Trade;
use ShidianUtil\Utils\TimeUtil;
use think\facade\Queue;

/**
 * 咨询服务
 * Class ConsultingServerService
 * @package app\index\service
 */
class ConsultingServerService
{

    /**
     * 激活免费咨询服务（赠送聊天次数和时长）
     * @param int $consultingId 咨询ID
     * @param int $serverId 需要激活的咨询服务ID
     * @return void
     */
    public function serverStartOfFree($consultingId, $serverId): void
    {

        $consulting = Consulting::where('id', $consultingId)->find();
        $server = ConsultingServer::where('id', $serverId)->where('serverType', ConsultingServer::FREE)->find();

        if (!$consulting || !$server) {
            return;
        }

        $memberId = $consulting->memberId;
        $questionId = $consulting->questionId;
        $maxTimes = $server->maxTimes;
        $now = time();
        $sTime = TimeUtil::stamp(TimeUtil::DAY, $now);
        $eTime = TimeUtil::stamp(TimeUtil::DAY, $sTime, false);

        if ($consulting->consultingType != '0') {
            return;
        }

        if (!is_id($questionId)) {
            return;
        }

        // 免费次数0 或者 追问次数0
        if ($maxTimes <= 0 || $server->questionsNum <= 0) {
            return;
        }

        // 查询问题
        $question = ConsultingQuestion::where('id', $questionId)->find();
        if (!$question) {
            return;
        }

        // 同问题其他咨询激活了免费咨询服务，本咨询也同样激活
        if ($question->freeConsultingServerId != 0) {
            $this->serverStartOfFree0($consulting, $server, null, $sTime, $eTime);
            return;
        }

        // 查询今天是否还有剩余的免费咨询次数
        $count = ConsultingQuestion::where('memberId', $memberId)
            ->where('freeConsultingServerId', '<>', 0)
            ->timeRange($sTime, $eTime, 'freeConsultingServerTime', 'freeConsultingServerTime')
            ->count();
        if ($count < $maxTimes) {
            $this->serverStartOfFree0($consulting, $server, $question, $sTime, $eTime);
            return;
        }
    }

    /**
     * 激活付费咨询服务（赠送聊天次数和时长）
     * @param int $consultingId 咨询ID
     * @param int $serverId 需要激活的咨询服务ID
     * @param int $tradeId 订单ID
     * @return void
     */
    public function serverStartOfPaid($consultingId, $serverId, $tradeId): void
    {

        $consulting = Consulting::where('id', $consultingId)->find();
        $server = ConsultingServer::where('id', $serverId)->find();
        $trade = Trade::where('id', $tradeId)->find();

        if (!$consulting || !$server) {
            return;
        }

        $now = time();

        // 畅聊时长
        $chatFreelyDuration = $server->chatFreelyDuration;

        // 如果是夜间(0:00 ~8:00)那么延长服务时间为24小时
        if (at_night($now)) {
            $chatFreelyDuration = 24;
        }

        // 订单保存服务生效时间
        if ($trade) {
            $trade->startTime = $now;
            $trade->save();

            // 订单24小时后结束任务
            if ($server->isChatFreely == 1) {
                $delay = $chatFreelyDuration * 3600 + 10;
            } else {
                $delay = 86400;
            }
            $job_data = ['id' => $trade->id];
            Queue::later($delay, TradeEnd::class, $job_data);
        }

        // 更新咨询的活动时间
        $lastActiveTime = time() + 24 * 3600;
        if ($server->isChatFreely == 1) {
            $lastActiveTime = time() + $chatFreelyDuration * 3600 + 24 * 3600;
        }
        $consulting->updateActiveTime($lastActiveTime);

        // 对应的咨询添加聊天时长和次数
        if ($server->isChatFreely == 1) {
            // 畅聊

            $isChatFreelyEndTime = $consulting->isChatFreelyEndTime;
            if ($isChatFreelyEndTime < $now) {
                $isChatFreelyEndTime = $now;
            }
            $isChatFreelyEndTime += $chatFreelyDuration * 3600;

            $consulting->isChatFreely = '1';
            $consulting->isChatFreelyEndTime = $isChatFreelyEndTime;
            $consulting->questionsNumRemind = 0;
            $consulting->save();

            // 给用户消息
            $content = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '支付成功，当前可用聊天时长',],
                    ['type' => 'text', 'red' => '101', 'text' => humanized_time_length($consulting->isChatFreelyEndTime - $now),],
                    ['type' => 'text', 'red' => '102', 'text' => '畅聊截止时间为：' . date('Y-m-d H:i', $consulting->isChatFreelyEndTime),],
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);

        }
        else {
            //次数

            $consulting->questionsNum += $server->questionsNum;
            $consulting->questionsNumRemind = 0;
            $consulting->save();

            // 给用户消息
            $content = [
                'templates' => [
                    ['type' => 'text', 'red' => '102', 'text' => '支付成功，当前可用聊天次数为：',],
                    ['type' => 'text', 'red' => '101', 'text' => $consulting->questionsNum . '次',]
                ],
            ];
            $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);
        }

    }


    private function serverStartOfFree0(Consulting $consulting, ConsultingServer $server, ?ConsultingQuestion $question, $sTime, $eTime)
    {
        // 享受服务的用户ID
        $memberId = $consulting->memberId;

        // 更新提问
        if ($question && !is_id($question->freeConsultingServerId)) {
            $question->freeConsultingServerId = $server->id;
            $question->freeConsultingServerTime = $sTime;
            $question->save();
        }

        // 更新咨询的活动时间
        $lastActiveTime = time() + 24 * 3600;
        $consulting->updateActiveTime($lastActiveTime);

        // ************** 聊天时长和次数 ******************

        // 赠送次数
        $consulting->questionsNum += $server->questionsNum;
        $consulting->freeNum += $server->questionsNum;
        $consulting->questionsNumRemind = 0;
        $consulting->save();

        // 发消息 获得免费次数
        $realname = Member::where('id', $consulting->lawyerId)->value('realname', '');
        $content = [
            'templates' => [
                ['type' => 'text', 'red' => '102', 'text' => $realname . '律师赠送您',],
                ['type' => 'text', 'red' => '101', 'text' => $consulting->questionsNum . '次',],
                ['type' => 'text', 'red' => '102', 'text' => '咨询次数您可以继续提问',],
            ],
        ];
        $this->getMessageSendService()->sendSystemMessage($consulting, $consulting->memberId, ConsultingMessage::SYSTEM, $content);

    }

    private function getMessageSendService(): MessageSendService
    {
        return app(MessageSendService::class);
    }

}
